package com.sundi.ecmarket.utils;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Component
public class UploadUtils {


    @Value("${imagePath}")
    private String imagePath;


    @Value("${imageUrl}")
    private String imageUrl;

    public List<String> upload(MultipartFile[] files) throws IOException {
        String originalFilename = "";
        String name = "";
        String newImageName = "";

        List<String> images = new ArrayList<>();
        if (files!=null){
            for (MultipartFile file :files) {
                originalFilename = file.getOriginalFilename();
                name = originalFilename.substring(originalFilename.lastIndexOf("."));
                newImageName = UUID.randomUUID().toString().concat(name);
                File file1 = new File(imagePath,newImageName);
                if (!file1.getParentFile().exists()){
                    file1.getParentFile().mkdirs();
                }
                file.transferTo(file1);
                images.add(imageUrl.concat(newImageName));
            }
        }
        return images;
    }
}
